package io.renren.modules.dishes.controller;




import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.modules.dishes.entity.ClassificationEntity;
import io.renren.modules.dishes.service.impl.ClassficationServiceImpl;
import io.renren.modules.merchant.service.impl.MerchantServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

import static io.renren.common.utils.ShiroUtils.getUserId;


@RestController
@RequestMapping("/web/classfication")
public class ClassficationController {
    @Autowired
    private ClassficationServiceImpl classficationService;
    @Autowired
    private MerchantServiceImpl merchantService;


    @GetMapping("/list")
    public R getClassfications(){
        Long userId = getUserId();
        String merchantId = merchantService.getMerchantByUserId(userId).getMerchantId();
        List<ClassificationEntity> list = classficationService.getClassficationByUserId(merchantId);
        return R.ok().put("list",list);
    }

    @GetMapping("/get/{id}")
    public R getClassfication(@PathVariable("id") String id){
        ClassificationEntity classficationById = classficationService.getClassficationById(id);
        return R.ok().put("classfication",classficationById);
    }

    @PostMapping("/save")
    public R saveClassfication(@RequestBody ClassificationEntity classfication){
        Long userId = getUserId();
        String merchantId = merchantService.getMerchantByUserId(userId).getMerchantId();
        classfication.setMerchantId(merchantId);
        String uuid = UUID.randomUUID().toString().replace("-", ""); // 移除短横线，得到32位
        String shortId = uuid.substring(0, 32); // 截取前32位
        classfication.setClassifyId(shortId);
        System.err.println(classfication);
        Integer integer = classficationService.saveClassfication(classfication);
        if (integer==0){
            return R.error("已有该分类");
        }
        return R.ok();
    }

    @PostMapping("/update")
    public R updateClassfication(@RequestBody ClassificationEntity classfication){
        QueryWrapper<ClassificationEntity> wrapper=new QueryWrapper<ClassificationEntity>()
                .eq("merchant_id",classfication.getMerchantId())
                .eq("classify_name",classfication.getClassifyName());
        ClassificationEntity classificationEntity = classficationService.getOne(wrapper);
        //如果有重复分类则返回错误
        if (classificationEntity!=null){
            return R.error("已有该分类");
        }else {
            classficationService.updateById(classfication);
            return R.ok();
        }
    }

    @RequestMapping("/delete/{id}")
    public R delete(@PathVariable String id){
        classficationService.deleteBuId(id);
        return R.ok();
    }

}
